package com.xiaobawang.xjsyy_idea_plugin.panel.dev_process.view;

import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
import java.awt.*;
import java.awt.event.MouseEvent;

public class TooltipLabel extends JLabel {

    private String bubbleText;
    private JComponent bubbleComponent;
    private Timer timer;
    private Point mousePosition;

    public TooltipLabel(String text, String bubbleText) {
        super(text);
        this.bubbleText = bubbleText;
        init();
    }

    public TooltipLabel(String text, JComponent bubbleComponent) {
        super(text);
        this.bubbleComponent = bubbleComponent;
        init();
    }

    private void init() {
        setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        addMouseListener(new MouseInputAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                mousePosition = e.getPoint();
                timer = new Timer(500, e1 -> showBubble());
                timer.setRepeats(false);
                timer.start();
            }

            @Override
            public void mouseExited(MouseEvent e) {
                if (timer != null) {
                    timer.stop();
                }
                hideBubble();
            }
        });
    }

    private void showBubble() {
        if (bubbleComponent == null) {
            bubbleComponent = createBubbleComponent(bubbleText);
        }
        int x = getWidth() - bubbleComponent.getWidth() - 10;
        int y = 0; // Position at top right corner
        popupBubble(x, y);
    }

    private void popupBubble(int x, int y) {
        JWindow bubbleWindow = new JWindow();
        bubbleWindow.add(bubbleComponent);
        bubbleWindow.setSize(bubbleComponent.getWidth(), bubbleComponent.getHeight());
        bubbleWindow.setLocationRelativeTo(this);
        bubbleWindow.setLocation(x + getX(), y + getY());
        bubbleWindow.setVisible(true);
    }

    private JComponent createBubbleComponent(String text) {
        JPanel bubblePanel = new JPanel();
        bubblePanel.setLayout(new BorderLayout());
        JLabel bubbleLabel = new JLabel(text);
        bubblePanel.add(bubbleLabel);
        return bubblePanel;
    }

    private void hideBubble() {
        if (bubbleComponent != null && bubbleComponent.getParent() instanceof JWindow) {
            ((JWindow) bubbleComponent.getParent()).dispose();
        }
    }
}